#include "back.h"
#include "global.h"
#include "manager.h"


back::back(){
	netfd = -1;
}
back::~back(){

}

void back::setFd(int fd){
	netfd = fd;
}
void back::setManager(manager * m){
	boss = m;
}

void back::input(){
	printf("back::input\n");

	int len = ::recv(netfd, buffer, 10240, 0);
	if( len == 0 ){
		boss->closeConn();
		return ;
	}else if (len < 0){
		printf("recv error\n");
		return ;
	}else if( len > 0 ){
		printf("msg:%s\n", buffer);
		boss->sendToFront(buffer, len);

	}
}
void back::output(){
	printf("back::output\n");

}
void back::timeout(){
	printf("back::timeout\n");

}

int back::setAddrInfo(const string&ip, int port){
	backip = ip;
	backport = port;
	printf("backip:%s, backport:%d\n", ip.c_str(), port);
	return 0;
}

int back::connect(const string &ip, int port){
	printf("back::connect\n");
	netfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if( netfd < 0 ){
		return -2;
	}

	struct sockaddr_in server_addr;
	bzero(&server_addr,sizeof(struct sockaddr_in));  
    server_addr.sin_family=AF_INET;  
	inet_aton(ip.c_str(), &server_addr.sin_addr);
   // server_addr.sin_addr = htonl(ip.c_str());  
    server_addr.sin_port = htons(port);  

	if( ::connect(netfd,(struct sockaddr *)(&server_addr),sizeof(struct sockaddr)) < 0 ){
		printf("back connect error\n");
		return -1;
	}
	
	int flags = ::fcntl(netfd, F_GETFL);  
    flags |= O_NONBLOCK;  
    fcntl(netfd, F_SETFL, flags);  

    event_set(&netEvent, netfd, EV_READ | EV_PERSIST , dataInput, (void *)this);  
	event_add(&netEvent, NULL); 
	
	return netfd;
}

int back::send(const char* msg, int msg_len){
	printf("back::send\n");
	if( netfd < 0 ){
		connect("127.0.0.1", 6667);
	}
	int ret = ::send(netfd, msg, msg_len, 0);
	return ret;
}

void back::close(){
	::close(netfd);
}


